package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.HuanXinTemplate;
import com.itheima.domain.db.*;
import com.itheima.service.db.*;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FriendService;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author zsk
 * @create 2022-03-21-17:22
 */
@Component
public class MessageManager {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private QuestionService questionService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendService friendService;

    @DubboReference
    private CommentService commentService;

    @DubboReference
    private AnnouncementService announcementService;

    @DubboReference
    private NotificationService notificationService;

    //通过环信发送消息
    public void strangerQuestions(long jiarenId, String reply) {

        //获取线程内UserId
        Long userId = UserHolder.get().getId();

        //查询用户昵称,根据UserInfo
        String nickname = userInfoService.findById(userId).getNickname();
        //根据jiarenId查询他的陌生人问题
        Question question = questionService.findByUserId(jiarenId);

        if (question == null) {
            question = new Question();
        }
        //组装json
        Map requestBody = new HashMap();
        requestBody.put("userId", userId);
        requestBody.put("huanXinId", "HX" + userId);
        requestBody.put("nickname", nickname);
        requestBody.put("strangerQuestion", question.getStrangerQuestion());
        requestBody.put("reply", reply);
        //转换为json消息
        String json = JSON.toJSONString(requestBody);

        //向环信发消息
        huanXinTemplate.sendMsg("HX" + jiarenId, json);

    }

    //同意好友申请
    public void addContacts(Long friendId) {

        //获取线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc建立mongo好友关系
        friendService.addFriend(userId, friendId);

        //调用环信建立好友关系
        huanXinTemplate.addContacts("HX" + userId, "HX" + friendId);

    }

    //查看好友列表
    public ResponseEntity findFriendByPage(Integer pageNum, Integer pageSize, String keyword) {

        //获取线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc查询好友分页对象
        PageBeanVo pageBeanVo = friendService.findFriendByPage(userId, pageNum, pageSize);

        //封装ContactVo对象
        List<ContactVo> voList = new ArrayList<>();

        //获取当前页对象
        List<Friend> friendList = (List<Friend>) pageBeanVo.getItems();
        //遍历
        if (CollectionUtil.isNotEmpty(friendList)) {
            for (Friend friend : friendList) {
                // 先把好友的信息查出来
                UserInfo userInfo = userInfoService.findById(friend.getFriendId());

                if (StrUtil.isNotEmpty(keyword)) {
                    if (userInfo.getNickname().contains(keyword)) {
                        // 创建vo
                        ContactVo vo = new ContactVo();
                        vo.setUserInfo(userInfo); // 好友信息
                        vo.setUserId("HX"+friend.getFriendId());// 好友的环信id
                        // 添加vo集合
                        voList.add(vo);
                    }
                }else{
                    // 创建vo
                    ContactVo vo = new ContactVo();
                    vo.setUserInfo(userInfo); // 好友信息
                    vo.setUserId("HX"+friend.getFriendId());// 好友的环信id
                    // 添加vo集合
                    voList.add(vo);
                }
            }
        }
        //添加到pageBeanVo中
        pageBeanVo.setItems(voList);

        //返回结果
        return ResponseEntity.ok(pageBeanVo);

    }

    //查看点赞人的信息
    public ResponseEntity likes(Integer pageNum, Integer pageSize, Integer commentType) {

        //查看线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc查看
        PageBeanVo pageBeanVo = commentService.findUserCommentByPage(userId, commentType, pageNum, pageSize);

        //获取封装集合
        List<UserCommentVo> voList = new ArrayList<>();

        //获取当前页对象
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(commentList)){
            for (Comment comment : commentList) {

                //根据id查询UserInfo
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                UserCommentVo vo = new UserCommentVo();
                vo.setAvatar(userInfo.getAvatar());//用户头像
                vo.setNickname(userInfo.getNickname());//用户昵称
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));//操作时间

                voList.add(vo);


            }
        }
        //添加到分页集合对象中
        pageBeanVo.setItems(voList);
        //返回pageBeanVo
        return ResponseEntity.ok(pageBeanVo);


    }

    //查看评论人消息
    public ResponseEntity comments(Integer pageNum, Integer pageSize, Integer commentType) {
        
        //获取线程内userId
        Long userId = UserHolder.get().getId();
        
        //调用rpc查询
        PageBeanVo pageBeanVo = commentService.findUserCommentByPage(userId, commentType, pageNum, pageSize);
        
        List<UserCommentVo> voList = new ArrayList<>();
        
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(commentList)){
            for (Comment comment : commentList) {

                //先查询userInfo信息
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                UserCommentVo vo = new UserCommentVo();
                vo.setAvatar(userInfo.getAvatar());//用户头像
                vo.setNickname(userInfo.getNickname());//昵称
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));//操作时间

                voList.add(vo);

            }
        }

        //存储到分页集合对象中
        pageBeanVo.setItems(voList);
        
        //返回分页集合对象
        return ResponseEntity.ok(pageBeanVo);


    }

    //喜欢列表
    public ResponseEntity loves(Integer pageNum, Integer pageSize, Integer commentType) {
        //获取线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc查询
        PageBeanVo pageBeanVo = commentService.findUserCommentByPage(userId, commentType, pageNum, pageSize);

        List<UserCommentVo> voList = new ArrayList<>();

        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(commentList)){
            for (Comment comment : commentList) {

                //先查询userInfo信息
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                UserCommentVo vo = new UserCommentVo();
                vo.setAvatar(userInfo.getAvatar());//用户头像
                vo.setNickname(userInfo.getNickname());//昵称
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));//操作时间

                voList.add(vo);

            }
        }

        //存储到分页集合对象中
        pageBeanVo.setItems(voList);

        //返回分页集合对象
        return ResponseEntity.ok(pageBeanVo);
    }

    //查看公告信息
    public ResponseEntity announcements(Integer pageNum, Integer pageSize) {
        //获取线程内userId
        Long userId = UserHolder.get().getId();
        Notification notification = notificationService.findByUserId(userId);
        if (notification.getGonggaoNotification() == false){//代表用户没有开启公告
            return ResponseEntity.status(500).body(ErrorResult.error());
        }
        //调用rpc分页查询
        PageBeanVo pageBeanVo = announcementService.findByPage(pageNum,pageSize);
        //创建一个通告集合，存储通告信息
        List<AnnouncementVo> voList = new ArrayList<>();
        //显示分页信息
        List<Announcement> announcementList = (List<Announcement>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(announcementList)){
            for (Announcement announcement : announcementList) {
                //取出announcement的id
                AnnouncementVo vo = new AnnouncementVo();
                vo.setId(String.valueOf(announcement.getId()));//设置返回id
                vo.setTitle(announcement.getTitle());//公告
                vo.setDescription(announcement.getDescription());//内容详情
                vo.setCreateDate(announcement.getCreated().toString());//公告创建时间
                //封装到集合对象中
                voList.add(vo);
            }
        }
        //添加到分页对象中
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }
}
